<!--  -->
<template>
    <div>

        <van-form @submit="onSubmit">

            <!-- 头部 -->
            <div class="font15 mt10">
                <div class="pl10">
                    <span class="titletext ">{{ params.isDrawup == '1' ? '项目进度起草' : nFromdata.title }}</span>
                </div>

                <div v-if="params.isDrawup != '1'" class="graytext mt10 mb5 font13 pl10">
                    <span>工单编号：</span>
                    <span class="titletext">{{ nFromdata.pmInsId }}</span>
                </div>

                <div v-if="params.isDrawup == '1'" class="redtext mt10 mb5 font13 pl10">
                    <span>提示：该表单带*字段都为必填项</span>
                </div>

                <div class="bcolor-e" style="height: 2px;"></div>
            </div>

            <section-header :sectionTitle="'项目信息'" />
            <div>
                <van-field label="项目名称:" name="projectName" v-model="mFromdata.projectName" label-width="4.5em" readonly
                    required input-align="left" :rules="[{ required: true, message: '' }]" />
                <van-field label="项目编码:" name="projectID" v-model="mFromdata.projectID" label-width="4.5em" readonly
                    required input-align="left" :rules="[{ required: true, message: '' }]" />
                <van-field label="集团名称:" name="customerName" v-model="mFromdata.customerName" label-width="4.5em"
                    readonly required input-align="left" :rules="[{ required: true, message: '' }]" />
                <van-field label="集团编码:" name="customerCode" v-model="mFromdata.customerCode" label-width="4.5em"
                    readonly required input-align="left" :rules="[{ required: true, message: '' }]" />
                <van-field label="地市:" name="city" v-model="mFromdata.city" label-width="2.5em" readonly required
                    input-align="left" :rules="[{ required: true, message: '' }]" />
                <van-field label="县区:" name="counties" v-model="mFromdata.counties" label-width="2.5em" readonly
                    required input-align="left" :rules="[{ required: true, message: '' }]" />
              <van-field readonly name="industryBigTypeProvince" :value="mFromdata.industryBigTypeProvince" label="省内行业大类：" label-width="7em" />
              <van-field readonly name="industryBigTypeGroup" :value="mFromdata.industryBigTypeGroup" label="集团行业大类：" label-width="7em" />
              <van-field readonly name="industryMinTypeGroup" :value="mFromdata.industryMinTypeGroup" label="集团行业小类：" label-width="7em" />
              <van-field readonly name="industryAttribution" :value="mFromdata.industryAttribution" label="15大行业名称：" label-width="7.5em" />
              <van-field readonly name="industryNameOneLevel" :value="mFromdata.industryNameOneLevel" label="行业一级名称：" label-width="7em" />
              <van-field readonly name="industryNameTwoLevel" :value="mFromdata.industryNameTwoLevel" label="行业二级名称：" label-width="7em" />
              <div v-if="showManagerOa" class="redtext font11" style="margin: 5px 15px 0px 15px;">
                    系统将为该角色推送收入确认工单，请谨慎选择。
                </div>
                <van-field v-if="showManagerOa" readonly required name="solutionManagerOa" :value="mFromdata.solutionManagerOa" label="解决方案经理账号:"
                    label-width="8.5em" :rules="[{ required: formEditable, message: '请选择解决方案经理账号' }]">
                    <template v-if="canEditManagerOa" #button>
                        <el-button size="small" type="primary" icon="el-icon-search"
                            @click="solutionManagerOaShowPopupView = true">选择人员</el-button>
                    </template>
                </van-field>
                <van-field v-if="showManagerOa" readonly required name="solutionManagerDepartment" :value="mFromdata.solutionManagerDepartment" label="解决方案经理部门:"
                    label-width="8.5em" :rules="[{ required: formEditable, message: '请选择解决方案经理账号' }]">
                </van-field>
                <get-user-org-list v-if="solutionManagerOaShowPopupView"
                    @update-flag="solutionManagerOaShowPopupView = false" @select-item="selectedUsersHandle" :maxNum="1" />

            </div>

            <section-header :sectionTitle="'里程碑信息'" />
            <div>
                <van-field label="里程碑节点:" name="milestoneNode" v-model="mFromdata.milestoneNode" label-width="5.5em"
                    readonly required :right-icon="formEditable ? 'arrow' : ''" @click="milestoneNodeClick()"
                    :rules="[{ required: true, message: '请选择里程碑节点' }]" />
                <van-popup v-model="milestoneNodeShowPopup" position="bottom" get-container="body">
                    <van-picker show-toolbar value-key="milestoneNode" :columns="milestoneNodeColumns"
                        @confirm="milestoneNodeClickConfirm" @cancel="milestoneNodeShowPopup = false">
                    </van-picker>
                </van-popup>

                <van-field label="计划完成时间:" name="planEndDate" v-model="mFromdata.planEndDate" label-width="7em" readonly
                    required input-align="left" :rules="[{ required: true, message: '' }]" />
                <van-field label="里程碑描述:" name="milestoneDescribe" v-model="mFromdata.milestoneDescribe"
                    label-width="5.5em" readonly required autosize type="textarea" rows="1" />
            </div>
            <!-- 拆分表 -->
            <section-header :sectionTitle="'拆分信息'" />
            <el-table :data="chaifenList" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }" border style="width: 100%">
                <el-table-column prop="contractSerialNumber" label="合同流水号" width="110" />
                <el-table-column prop="contractType" label="合同类型" width="110" />
                <el-table-column prop="splitBusinessType" label="业务大类" width="110" />
                <el-table-column prop="splitSujectName" label="账单名称" width="110" />
                <el-table-column prop="splitSujectCode" label="账单代码" />
                <el-table-column prop="isUniversal" label="是否属于通服收入" width="100" />
                <el-table-column prop="splitTaxRate" label="税率" width="100" />
                <el-table-column prop="splitIncludedAmount" label="含税总金额（元）" width="100" />  
                <el-table-column prop="splitNoAmount" label="不含税金额（元）" width="100" />  
                <el-table-column prop="splitTaxAmount" label="税额" width="100" />  
                <el-table-column prop="paymentType" label="出账类型" width="100" />  
                <el-table-column prop="billingTime" label="计费时长(月)" width="100" />
                <el-table-column prop="splitStartDate" label="计划起始日期" width="100" />  
                <el-table-column prop="splitEndDate" label="计划结束日期" width="100" /> 
                <el-table-column prop="contractPhase" label="合同约定计费阶段" width="100" />
            </el-table>
            <section-header :sectionTitle="'项目进度'" />
            <div>
              <van-field readonly name="contractSignatureDate" :value="mFromdata.contractSignatureDate" label="项目首次签约时间：" label-width="9em"/>
              <van-field label="逾期状态:" name="postponeStatus" v-model="mFromdata.postponeStatus" label-width="4.5em" readonly required input-align="left" :rules="[{ required: true, message: '' }]" />
              <van-field v-if="this.mFromdata.postponeStatus == '逾期'" label="逾期原因:" name="postponeCause" v-model="mFromdata.postponeCause" label-width="4.5em" :readonly="!formEditable" required :rules="[{ required: formEditable, message: '请输入逾期原因' }]" />
              <van-field v-if="isYSZY" label="收入合同含税总金额（元）:" name="incomeContractAmount" v-model="mFromdata.incomeContractAmount" label-width="12.5em" readonly />
              <van-field v-if="isYSZY" label="项目交付时长（天）:" name="projectDeliveryTime" v-model="mFromdata.projectDeliveryTime" label-width="9.5em" readonly />
              <van-field label="完成人姓名:" name="actualDeliverer" v-model="mFromdata.actualDeliverer" label-width="5.5em" readonly required input-align="left" :rules="[{ required: true, message: '' }]" />
              <van-field label="完成人OA账号:" name="actualDelivererAcount" v-model="mFromdata.actualDelivererAcount" label-width="7.5em" readonly required input-align="left" :rules="[{ required: true, message: '' }]" />
              <div>
                <van-field label-width="10em" readonly label="进度证明材料:" class="lyy-width" required>
                  <template #button v-if="formEditable">
                    <van-button native-type="button" style="margin:0 13px 0 0px;"
                                @click="processProveFileOCRClick()" size="small" type="primary">OCR识别</van-button>
                    <van-uploader :after-read="didFinishPickingFiles">
                      <van-button native-type="button" size="small"
                                  type="primary">AI+</van-button>
                    </van-uploader>
                  </template>
                </van-field>
                <div v-for="(fileitem, index) in mFromdata.processProveFile" :key="fileitem.id"
                     style="margin-left:20px">
                  <div readonly class="font14 fileLink" style="color:#0F85CF">
                    <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName
                      }}</a>
                  </div>
                  <van-icon v-if="formEditable" name="close" color="#ea0023" size="20" @click="deleteFile(index)"></van-icon>
                </div>
              </div>
              <van-field label-width="10em" readonly label="交付物证明材料:" class="lyy-width" input-align="left" placeholder=""/>
              <div v-for="(fileitem) in mFromdata.deliverablesFile" :key="fileitem.id" style="margin-left:20px">
                <div readonly class="font14 fileLink" style="color:#0F85CF">
                  <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{fileitem.fileName}}</a>
                </div>
              </div>
                <van-field label="验收结果:" name="checkStateName" v-model="mFromdata.checkStateName" label-width="4.5em"
                    readonly required placeholder="请选择" :right-icon="formEditable ? 'arrow' : ''"
                    @click="checkStateShowPopup = formEditable"
                    :rules="[{ required: formEditable, message: '请选择验收结果' }]" />
                <van-popup v-model="checkStateShowPopup" position="bottom" get-container="body">
                    <van-picker show-toolbar value-key="value" :columns="checkStateColumns"
                        @confirm="checkStateClickConfirm" @cancel="checkStateShowPopup = false">
                    </van-picker>
                </van-popup>

                <van-field v-if="!isNBCS" label="通过时间:" name="actualDeliveryTime" v-model="mFromdata.actualDeliveryTime"
                    label-width="4.5em" readonly required :right-icon="formEditable ? 'arrow' : ''"
                    @click="actualDeliveryTimeShowPopup = formEditable"
                    :rules="[{ required: formEditable, message: '请选择通过时间' }]" />
                <van-popup v-model="actualDeliveryTimeShowPopup" position="bottom" get-container="body">
                    <van-datetime-picker v-model="currentDate" :formatter="formatter" type="date"
                        @confirm="actualDeliveryTimeComfirm"
                        @cancel="actualDeliveryTimeShowPopup = false"></van-datetime-picker>
                </van-popup>

                <van-field v-if="isNBCS" label="内部测试时间:" name="internalTestingDate"
                    v-model="mFromdata.internalTestingDate" label-width="6.5em" readonly required input-align="left"
                    :rules="[{ required: true, message: '' }]" />
                <van-field v-if="isSZFP" label="售中复盘内容:" name="onReview" v-model="mFromdata.onReview"
                    label-width="6.5em" readonly required autosize type="textarea" rows="1" />
                <van-field v-if="isSZFP" label-width="10em" readonly label="售中复盘文件:" class="lyy-width"
                    input-align="left" required placeholder="" />
                <div v-for="(fileitem) in mFromdata.onReviewFile" :key="fileitem.id" style="margin-left:20px">
                    <div v-if="isSZFP" readonly class="font14 fileLink" style="color:#0F85CF">
                        <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName
                            }}</a>
                    </div>
                </div>
                <van-field v-if="isNBCS" label-width="10em" readonly label="内部测试报告:" class="lyy-width"
                    input-align="left" required placeholder="" />
                <div v-for="(fileitem) in mFromdata.internalTestingFile" :key="fileitem.id" style="margin-left:20px">
                    <div v-if="isNBCS" readonly class="font14 fileLink" style="color:#0F85CF">
                        <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName
                            }}</a>
                    </div>
                </div>
                <van-field label="验收报告是否为空:" name="isProveFileNull" v-model="mFromdata.isProveFileNull"
                    label-width="8.5em" readonly required input-align="left"
                    :rules="[{ required: formEditable, message: '请输入验收报告是否为空' }]" />
                <van-field label="是否有签章:" name="isSignature" v-model="mFromdata.isSignature" label-width="5.5em"
                    readonly required input-align="left" :rules="[{ required: formEditable, message: '请输入是否有签章' }]" />
                <van-field label="签章是否异常:" name="isSignatureCorrect" v-model="mFromdata.isSignatureCorrect"
                    label-width="6.5em" readonly required input-align="left"
                    :rules="[{ required: formEditable, message: '请输入签章是否异常' }]" />


                <van-field label="备注:" name="remark" v-model="mFromdata.remark" label-width="2.5em" readonly
                    input-align="left" />

            </div>
            <div v-if="aiDataResult&&aiDataResult.resultData&&!sysFiles&&sysFiles.length<1">
              <ai-el-table :aiDataResult="aiDataResult"></ai-el-table>
            </div>
            <div v-else-if="formEditable&&sysFiles&&sysFiles.length>0">
              <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
                <div class="blue_item" />
                <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">AI解析结果</span>
              </div>
              <el-table  :data="sysFiles" border style="width: 100%">
                <el-table-column prop="fileName" width="100px" label="文档名称" />
                <el-table-column prop="creator" label="上传人" />
                <el-table-column prop="createdTime" label="上传时间" />
                <el-table-column prop="state" label="AI解析状态" />
              </el-table>
              <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
                <div class="blue_item" />
                <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">AI解析详情</span>
              </div>
              <el-table  :data="analysisData" border style="width: 100%">
                <el-table-column type="index" width="40px" label="序号" />
                <el-table-column prop="fieldName" label="关键字段名称" />
                <el-table-column prop="dictValue" label="DICT系统数据" />
                <el-table-column label="AI解析结果" >
                  <template v-slot:default="scope">
                    <div v-if="Array.isArray(scope.row.aiOldValue) && scope.row.aiOldValue.length>0&&isBase64(scope.row.aiOldValue[0])" >
                      <div v-for="(item,index) in scope.row.aiOldValue" :key="index">
                        <img :src="'data:image/jpg;base64,'+item" style='width:50px;margin-left:5px;cursor:pointer;'>
                      </div>
                    </div>
                    <div v-else class="w100 f-1">
                      <div>{{scope.row.aiOldValue}}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="equalResult" label="一致性对比结果" >
                  <template v-slot:default="scope">
                    <div class="w100 f-1">
                      <div v-if="scope.row.equalResult=='不一致'" style="color: red">{{scope.row.equalResult}}</div>
                      <div v-else-if="scope.row.equalResult=='一致'" style="color: green">{{scope.row.equalResult}}</div>
                      <div v-else>{{scope.row.equalResult}}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="editValue" label="人工修正AI解析结果" width="200" align="center">
                  <template slot-scope="scope">
                    <van-field v-model="scope.row.editValue" rows="1" autosize label="" type="textarea" placeholder="请输入修正内容" @blur="editValueChange(scope.$index,scope.row.editValue)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 跳转意见 -->
            <div v-if="showOpinionMoudle" class="left_botton">
                <button block type="button" @click="tomsg()" style="color:#60a9ec; display: inline-block;width:100%;border: 0px solid #60a9ec;border-radius: 15px 0px 0px 15px;
            padding:10px 10px 10px 15px;font-size:13px">意见</button>
            </div>

            <!-- 流转下一步 -->
            <div v-if="showNextButton" class="footer">
                <van-button block type="info" native-type="submit"
                    style="display: inline-block; width: 100%; border: 0px solid #60a9ec">{{ buttonTitle }}</van-button>
            </div>
        </van-form>


        <!-- 当前办理人 -->
        <section-header v-if="showHistoryMoudle" :sectionTitle="'当前办理人'" />
        <div v-if="showHistoryMoudle" class="font13 ptandpb10 pl16">
            <div>
                <span class="titletext font13">{{
            historydata.MANAGER
        }}</span>
            </div>
            <div class="mt5">
                <span class="graytext font12">{{ historydata.DEPARTMENT }}</span>
            </div>
        </div>


        <!-- 审批意见 -->
        <section-header v-if="showOpinionMoudle" id="opinion" :sectionTitle="'审批意见'" />
        <opinion-item v-if="showOpinionMoudle" :approveList="approveList" />


        <!-- 底部占位 -->
        <div v-if="!showOpinionMoudle" style="padding-bottom: 42px"></div>

    </div>
</template>


<script>

import { mapGetters } from "vuex";
import { Dialog, Notify, Toast } from "vant";
import { openFileUrl } from "@/store/openFile";
import util from "@/assets/js/public";
import {
  getSZTDZJFormDetail,
  findProjectProcessModelByProjectID,
  getWfOptMags,
  getWfLinkTracks,

  verifyProjectMilestoneNodes,
  projectMilestoneFindAll,
  findOnSaleTeamManageByProjectId,
  uploadFileCommon,
  sealCheckWithOCR,
  getAnalysisByProjectEstablishNumberAndContractPhase,
  findByUsername, fileParsingCurrencyHttp, fileParsingRequestAnalysisFlowQuery, saveFileParsingRequestLog
} from "@/api/dictapi";
import SectionHeader from '../sztdzj/sztdzjDetail/section-header.vue';
import OpinionItem from '../sztdzj/sztdzjDetail/opinion-item.vue';
import moment from "moment";
import jTool from '../../assets/js/jHelper';
import getUserOrgList from "@/components/getuserorg_list/index.vue";
import aiElTable from "@/components/aiElTable/index.vue";
import aiUtils from "@/assets/js/aiUtils";

export default {
    data() {
        return {

            params: {},
            todotype: false,
            toRead: false,
            approveList: [],
            historydata: {},


            nFromdata: {},
            mFromdata: { isProveFileNull: '', isSignature: '', isSignatureCorrect: '', milestoneNode: '', planEndDate: '', milestoneDescribe: '' },

            milestoneNodeShowPopup: false,
            milestoneNodeColumns: [],

            checkStateShowPopup: false,
            checkStateColumns: [{ 'name': '已完成', 'value': '已通过' }, { 'name': '未通过', 'value': '未通过' }],

            actualDeliveryTimeShowPopup: false,
            currentDate: new Date(),

            buttonTitle: '流转下一步',
            canToNext: true,
            //计费下沉新增
            chaifenList:[],
            solutionManagerOaShowPopupView:false,
            showManagerOa:false,
            isEnd:false,
            canEditManagerOa:false,
            aiDataResult:{},
            analysisCode:'',
            sysFiles:[],
            analysisData:[],
            idKey:''
        };
    },

    computed: {

        ...mapGetters(["user"]),

        /// 里程碑节点 == 内部测试
        isNBCS() {
            return this.mFromdata.milestoneNode == '内部测试';
        },

        /// 里程碑节点 == 售中复盘
        isSZFP() {
            return this.mFromdata.milestoneNode == '售中复盘';
        },

        /// 里程碑节点 == 终验、验收
        isYSZY() {
            return this.mFromdata.milestoneNode == '终验' || this.mFromdata.milestoneNode == '验收';
        },

        formEditable() {
            return this.params.location === 'dict.start' || this.params.isDrawup == '1';
        },

        /// 意见
        showOpinionMoudle() {
            return this.params.isDrawup != '1';
        },

        showHistoryMoudle() {
            return this.params.todoType == "2" && this.historydata?.MANAGER && this.params.isDrawup != '1';
        },

        showNextButton() {
            return this.todotype || this.toRead || this.params.isDrawup == '1';
        }

    },

    //生命周期--创建完成
    created() {
        /// 办理 - 从待办进来（界面每次都会重新创建，所以不需要考虑缓存的问题）
        if (this.$route.query.isDrawup != '1') {

            this.params = this.$route.query;
            if (this.params.pmInsType == null && this.params.processType != null) {
                this.params.pmInsType = this.params.processType
            }
            if (this.params.location=='dict.toStart'){
              this.isEnd = true;
            }
            if (this.params.todoType == "1") {
                this.todotype = true;
                if (this.isEnd == true){
                  this.canEditManagerOa = true;
                }
            }
            else if (this.params.todoType == "3") {
                this.toRead = true;
            }

            this.getdetail();
        }


    },


    beforeRouteEnter(to, from, next) {

        next(vm => {

            // console.log('AA', to, 'AAAA', from);
            // 起草 - 从二级”项目进度列表“进来（界面因为保活问题，第二次从”项目进度列表“进来的时候 created方法不会重新调用，所以需要确保”项目进度列表“进来（或唤醒）时，要刷新起草数据）
            // 通过 `vm` 访问组件实例
            if (to.query.isDrawup == '1' && from.name === 'drawup_xmjd_tab') {
                vm.params = to.query;
                vm.requestDrawupInfo(to.query.projectId);
            }
        });
    },



    //生命周期--挂载完成
    components: {
      aiElTable,
        SectionHeader,
        OpinionItem,
        getUserOrgList
    },

    //生命周期--挂载完成
    mounted() { },

    //方法调用
    methods: {
        editValueChange(index,value){
          if (this.analysisData[JSON.stringify(index)].dictValue==value){
            this.analysisData[JSON.stringify(index)].equalResult='一致'
          }
          this.analysisData=JSON.parse(JSON.stringify(this.analysisData))
        },
        // 方案经理 - 选人回调
        selectedUsersHandle(list) {
            this.stakeholderNameShowPopupView = false;
            let user = list[0];
            if (user) {
              Toast.loading({ message: "加载中", forbidClick: false });
              this.requestStakeholderUserInfo(user.id);
            }
        },
        // 方案经理 - 人员信息
        requestStakeholderUserInfo(username) {
            findByUsername(username).then((result) => {
                    Toast.clear();
                    let data = result.data.data;
                    let message = result.data.message;
                    if (data) {
                        this.mFromdata.solutionManagerDepartment = data.belongDepartmentName;
                        this.mFromdata.solutionManagerOa = data.username;
                        this.$forceUpdate();
                    }
                    else {
                        if (jTool.stringIsEmpty(message)) {
                            message = '获取人员信息失败,请稍后重试';
                        }
                        Notify({ type: 'warning', message: message })
                    }
                })
                .catch((error) => {
                    Toast.clear();
                    Notify({ type: 'warning', message: '获取人员信息失败,请稍后重试' })
                });
        },
        tomsg() {
            document.getElementById('opinion').scrollIntoView({ behavior: 'smooth' })
        },

        openFileUrlfun(value) {
            this.$router.push({
                name: "fileview",
                query: {
                    openFileUrl: openFileUrl(value),
                },
            });
        },

        getdetail() {
            Toast.loading({ message: "加载中", forbidClick: false });
            getSZTDZJFormDetail(
                Object.assign(this.params, { userName: this.user.userName })
            ).then((result) => {
                this.fromdetal = {};
                Toast.clear();

                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {
                    this.nFromdata = result.data.data;
                }

                this.getDecisionMakingByPmInsId(result.data.data.projectInformationId);
            })

            getWfOptMags(Object.assign(this.params), {
                userName: this.user.userName,
            }).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }
                this.approveList = result.data.data.reverse();
            })

            if (this.params.todoType == "2") {

                getWfLinkTracks(Object.assign(this.params), {
                    userName: this.user.userName,
                }).then((result) => {
                    Toast.clear();
                    if (!result.data) {
                        Notify(result.message);
                        return;
                    }
                    if (result.data.data) {
                        //数据过滤，并生成新的数组
                        this.historydata = result.data.data.filter(
                            (item) => item.CURRENTSTATE == 10
                        )[0];
                    }
                })
            }
        },

        getDecisionMakingByPmInsId(value) {

            findProjectProcessModelByProjectID(
                Object.assign(this.params, { userName: this.user.userName, projectProcessId: value })
            ).then((result) => {
                this.fromdetal = {};
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {
                    this.mFromdata = result.data.data;
                    this.mFromdata.checkStateName = this.getRealCheckStateName();
                    this.getAnalysisByProjectEstablishNumberAndContractPhase(result.data.data)
                    if(this.mFromdata.processProveFile){
                      Toast.loading({ message: "加载中", forbidClick: false, });
                      fileParsingRequestAnalysisFlowQuery(Object.assign(this.params, { userName: this.user.userName, fileId: this.mFromdata.processProveFile[0].id })).then((result) => {
                        Toast.clear();
                        if (!result.data) {
                          Notify(result.message);
                          return;
                        }
                        if (result.data.data) {
                          this.aiDataResult = result.data.data;
                        }
                      });
                    }
                }
            });
        },

        getRealCheckStateName() {

            if (!jTool.stringIsEmpty(this.mFromdata.checkState)) {
                return this.mFromdata.checkState != '已完成' ? '未通过' : '已通过'
            }
            else {

                return '';
            }
        },



        /// 项目进度 获取数据
        /// 获取项目所有的里程碑节点信息 - 获取需要的里程碑节点信息 - 获取发起人信息
        requestDrawupInfo() {

            Toast.loading({ message: "加载中", forbidClick: false });
            projectMilestoneFindAll(this.params.projectId).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {

                    let content = result.data.data.content;
                    if (content && content.length > 0) {

                        /// 通过所有的里程碑节点 获取需要的里程碑节点信息
                        let detailData = content[0];
                        let milestoneMode = detailData.milestoneMode;
                        if (milestoneMode && milestoneMode.length > 0) {
                            this.requestDrawupInfoTwo(milestoneMode);
                        }
                        else {
                            Notify('无里程碑节点信息！');
                        }

                        detailData.customerName = detailData.customerUnitName;
                        detailData.customerCode = detailData.customerId;
                        this.mFromdata = Object.assign({}, this.mFromdata, detailData);
                    }
                    else {
                        Notify('获取项目信息失败，请重试！');
                    }
                }
            });

            findOnSaleTeamManageByProjectId(this.params.projectId).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {

                    let detailData = {};
                    detailData.actualDeliverer = result.data.data.TRUENAME;
                    detailData.actualDelivererAcount = result.data.data.USERNAME;

                    this.mFromdata = Object.assign({}, this.mFromdata, detailData);
                }
            });
        },

        requestDrawupInfoTwo(milestoneMode) {

            verifyProjectMilestoneNodes(milestoneMode).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {
                    this.milestoneNodeColumns = result.data.data;
                    this.configMilestoneInfo(result.data.data[0]);
                }
            });
        },

        // 配置“里程碑信息”的值
        configMilestoneInfo(obj) {

            this.mFromdata.milestoneNode = obj.milestoneNode;
            this.mFromdata.planEndDate = obj.planEndDate;
            this.mFromdata.milestoneDescribe = obj.milestoneDescription;
            getAnalysisByProjectEstablishNumberAndContractPhase(obj.milestoneNode,obj.projectID).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }
                if (result.data.data) {
                    this.chaifenList = result.data.data;
                }
            });
        },
        //获取拆分表内容
        getAnalysisByProjectEstablishNumberAndContractPhase(obj) {
            getAnalysisByProjectEstablishNumberAndContractPhase(obj.milestoneNode,obj.projectID,obj.pmInsId).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }
                if (result.data.data) {
                    this.chaifenList = result.data.data;
                    if (this.isEnd==true){
                      for(var i=0;i<result.data.data.length;i++){
                        if(result.data.data[i].contractPhase==this.mFromdata.milestoneNode ){
                          this.showManagerOa=true
                        }
                      }
                    }
                }
            });
        },
        milestoneNodeClick() {

            if (this.formEditable) {
                if (this.milestoneNodeColumns === undefined ||
                    this.milestoneNodeColumns === null ||
                    this.milestoneNodeColumns.length == 0) {

                    Toast({ type: 'text', message: '无更多的里程碑节点', duration: 1000 });
                }
                else {
                    this.milestoneNodeShowPopup = true;
                }
            }
        },

        milestoneNodeClickConfirm(value) {

            this.milestoneNodeShowPopup = false;
            this.configMilestoneInfo(value);
        },

        checkStateClickConfirm(value) {

            console.log(value);
            this.checkStateShowPopup = false;
            this.mFromdata.checkState = value.name;
            this.mFromdata.checkStateName = this.getRealCheckStateName();
        },

        /// 年月日 时间格式
        formatter(type, val) {
            if (type === 'year') {
                return `${val}年`;
            }
            else if (type === 'month') {
                return `${val}月`;
            }
            else if (type === 'day') {
                return `${val}日`;
            }

            return val;
        },

        actualDeliveryTimeComfirm(value) {

            this.actualDeliveryTimeShowPopup = false;

            let actualDeliveryTime = moment(value).format('YYYY-MM-DD');
            this.currentDate = actualDeliveryTime;
            this.mFromdata.actualDeliveryTime = actualDeliveryTime;

            // 时间对比、日期对比
            // 对比计划开工时间，大于则 逾期
            let planEndDate = new Date(this.mFromdata.planEndDate);
            if (value - planEndDate > 0) {
                this.mFromdata.postponeStatus = '逾期';
            }
            else {
                this.mFromdata.postponeStatus = '未逾期';
            }

            // 项目交付时长 = 通过时间 - 合同签订日期
            let contractSignatureDate = new Date(this.mFromdata.contractSignatureDate);
            let diffInDays = Math.floor((value - contractSignatureDate) / (1000 * 60 * 60 * 24));
            this.mFromdata.projectDeliveryTime = diffInDays;
        },

        // 网络请求 附件的OCR识别
        processProveFileOCRClick() {

            let fileDatas = this.mFromdata.processProveFile;
            let param = { 'fileData': fileDatas, 'projectEstablishNumber': this.mFromdata.projectID };
            if (fileDatas == null || fileDatas.length == 0) {
                Notify({ type: 'warning', message: '请先上传文件' });
                return;
            }

            Toast.loading({ message: "OCR识别...", forbidClick: false });
            sealCheckWithOCR(param).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                let responseData = result.data.data;
                let message = result.data.message;
                if (responseData) {

                    let result = responseData.result;   // 是否通过
                    let num = responseData.sealSize;    // 缺失的公章数量

                    this.mFromdata.isProveFileNull = result ? '否' : (num == 0 ? '是' : '否');
                    this.mFromdata.isSignature = result ? '是' : (num == 0 ? '否' : '是');
                    this.mFromdata.isSignatureCorrect = result ? '否' : '是';

                    Dialog.alert({ title: "提示", message: message });
                }
                else {
                    Notify({ type: 'warning', message: message });
                }
            });

        },

        /// 本地文件选中后的回调
        didFinishPickingFiles(file) {

            let fileData = new FormData();
            fileData.append("pmInsType", this.pmInsType);
            fileData.append("pmInsTypePart", "1");
            fileData.append("files", file.file);

            let params = new Map();
            params.pmInsType = this.pmInsType;
            params.pmInsTypePart = '1';
            params.userName = this.user.userName;
            Toast.loading({ message: "上传中", forbidClick: false });
            uploadFileCommon(fileData, params).then((res) => {
                Toast.clear();
                if (!res.data) {
                    Notify(res.message);
                    return;
                }
                if (res.data.data) {
                    if (this.mFromdata.processProveFile === null ||
                        this.mFromdata.processProveFile === undefined) {
                        this.mFromdata.processProveFile = [];
                    }

                    console.log('AaAKApiToken', this.mFromdata.processProveFile);
                    this.mFromdata.processProveFile=res.data.data.sysFiles
                    this.analysisCode=''
                    if (this.mFromdata.milestoneNode == '终验' || this.mFromdata.milestoneNode == '验收'){
                      this.analysisCode='YanShouJieXi'
                    }else {
                      this.analysisCode='JinDuJieXi'
                    }
                    Dialog.confirm({ title: "提示", message: "是否使用AI大模型能力对文件进行解析？" })
                        .then(() => {
                          let projectIdV = "";
                          if(this.mFromdata.projectID){
                            projectIdV=this.mFromdata.projectID
                          }else if (this.mFromdata.projectEstablishNumber){
                            projectIdV=this.mFromdata.projectEstablishNumber
                          }
                          let businessId = "";
                          if(this.mFromdata.businessId){
                            businessId=this.mFromdata.businessId
                          }
                          Toast.loading({
                            message: '解析中...',
                            forbidClick: false,
                          });
                          fileParsingCurrencyHttp(Object.assign(this.params, { userName: this.user.userName,businessId:businessId ,projectId: projectIdV, fileId: res.data.data.sysFiles[0].id ,analysisCode: this.analysisCode})).then((result) => {
                            Toast.clear();
                            if (!result.data) {
                              Notify(result.message);
                              return;
                            }
                            if (result.data.data) {
                              this.sysFiles=[]
                              this.sysFiles=res.data.data.sysFiles
                              this.analysisData=[]
                              if (result.data.data) {
                                this.idKey = result.data.data.id;
                                for(var i in result.data.data){
                                  if(i != "id"){
                                    if  (Array.isArray(result.data.data[i])&&result.data.data[i].length<1){
                                      this.analysisData.push({
                                        fieldName: i,
                                        aiOldValue: '[]',//AI解析原数据
                                        aiValue: '[]'//将AI解析的数据进行格式化
                                      });
                                    }else {
                                      this.analysisData.push({
                                        fieldName: i,
                                        aiOldValue: result.data.data[i],//AI解析原数据
                                        aiValue: aiUtils.valueFormatter(result.data.data[i])//将AI解析的数据进行格式化
                                      });
                                    }
                                  }
                                }
                                this.sysFiles[0].state = "执行成功";
                              }else {
                                this.sysFiles[0].state = "执行失败";
                              }
                              if (this.analysisCode=='YanShouJieXi'){
                                for(var i in this.analysisData){
                                  this.analysisData[i].dictField = "aiMark"+(parseInt(i)+1);//字段标识
                                  this.analysisData[i].dictValue = this.setYanShouJieXiValueData(this.analysisData[i]);
                                  this.analysisData[i].editValue = "";
                                }
                              }else {
                                for(var i in this.analysisData){
                                  this.analysisData[i].dictField = "aiMark"+(parseInt(i)+1);//字段标识
                                  this.analysisData[i].dictValue = this.setJinDuJieXiValueData(this.analysisData[i]);
                                  this.analysisData[i].editValue = "";
                                }
                              }

                              for(var i in this.analysisData){
                                var dictValue = this.analysisData[i].dictValue;
                                console.log('this.analysisData[i].dictValue'+this.analysisData[i].dictValue)
                                // 时间特殊处理
                                if(this.analysisData[i].dictValue.indexOf("-")>-1 && this.analysisData[i].dictValue.indexOf(":")>-1){
                                  dictValue = this.analysisData[i].dictValue.split(" ")[1];
                                }
                                // 比率
                                if(dictValue.indexOf("%") > -1){
                                  var num_regxa = /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/;//数字
                                  var dictNumStr = dictValue.replace("%","");
                                  if(num_regxa.test(dictNumStr)){
                                    dictValue = dictNumStr;
                                  }
                                }
                                var aiValue = this.analysisData[i].editValue?this.analysisData[i].editValue:(this.analysisData[i].aiValue?this.analysisData[i].aiValue:"");

                                // 判断DICT系统数据和集团数据是否一致
                                if(this.analysisData[i].dictValue=="未提及" || this.analysisData[i].aiValue=="未提及"){
                                  this.analysisData[i].equalResult = "不涉及";
                                }else{
                                  this.analysisData[i].equalResult = dictValue==aiValue?"一致":"不一致";
                                }
                                this.analysisData[i].editValue = this.analysisData[i].editValue || "";
                              }
                            }
                          });
                        })
                        .catch(() => { });
                }
            });
        },
        setJinDuJieXiValueData(data){ //JinDuJieXi-非 验收/终验阶段
          var valueInfos=''
          console.log("需要对应的名字是"+data.fieldName)
          if(data.fieldName == '项目名称'){
            valueInfos= this.mFromdata.projectName
          }else if(data.fieldName == '进度证明落款日期'){
            this.mFromdata.actualDeliveryTime=data.aiValue
            valueInfos= data.aiValue
          }else if(data.fieldName == '客户签名'){
            valueInfos= this.mFromdata.customerName
          }else if(data.fieldName == '进度截止日期'){
            valueInfos= this.mFromdata.planEndDate
          }else if(data.fieldName == '客户盖章'){
            this.mFromdata.meetingTime=data.aiValue
            valueInfos= data.aiValue
          }else if(data.fieldName == '签收日期'){
            this.mFromdata.actualDeliveryTime=data.aiValue
            valueInfos= data.aiValue
          }
          if (!valueInfos){
            valueInfos='未提及'
          }
          return valueInfos
        },
        setYanShouJieXiValueData(data){ //YanShouJieXi-验收/终验阶段
          var valueInfos=''
          console.log("需要对应的名字是"+data.fieldName)
          if(data.fieldName == '项目名称'){
            valueInfos= this.mFromdata.projectName
          }else if(data.fieldName == '客户签名'){
            valueInfos= ''
          }else if(data.fieldName == '移动方签名'){
            valueInfos= ''
          }else if(data.fieldName == '落款日期'){
            this.mFromdata.actualDeliveryTime=data.aiValue
            valueInfos= data.aiValue
          }else if(data.fieldName == '客户盖章'){
            valueInfos= this.mFromdata.customerName
          }else if(data.fieldName == '验收方签名'){
            valueInfos= ''
          }else if(data.fieldName == '客户名称'){
            valueInfos= this.mFromdata.customerName
          }else if(data.fieldName == '移动方盖章'){
            valueInfos= ''
          }else if(data.fieldName == '验收结论'){
            this.mFromdata.checkStateName = data.aiValue;
            if (data.aiValue.indexOf("不")>-1){
              this.mFromdata.checkState = '未通过';
            }else {
              this.mFromdata.checkState = '已完成';
            }
            valueInfos= data.aiValue
          }else if(data.fieldName == '验收方盖章'){
            valueInfos= this.mFromdata.customerName
          }
          if (!valueInfos){
            valueInfos='未提及'
          }
          return valueInfos
        },
        // 判断是否是base64编码
        isBase64(str){
          var regex = /^(?:[A-Za-z0-9+/]{4})*?(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/;
          return regex.test(str);
        },
        deleteFile(index) {
            Dialog.confirm({ title: "提示", message: "是否删除此附件？" })
                .then(() => {
                    this.mFromdata.processProveFile.splice(index, 1);
                })
                .catch(() => { });
        },

        // 流转下一步
        onNext() {

            if (this.mFromdata.processProveFile == null || this.mFromdata.processProveFile.length == 0) {
                Toast({ type: 'text', message: '请上传进度证明材料', duration: 1000 });
                return;
            }

            // if (this.mFromdata.isSignatureCorrect != '否') {
            //     Toast({ type: 'text', message: 'OCR 识别有误，请重试', duration: 1000 });
            //     return;
            // }


            //提交流转
            console.log("传给递交页面:", this.params)
            console.log("formDataformData", JSON.stringify(this.mFromdata));
            var formSendData = { "htmlParamMap": {} };
            formSendData.htmlParamMap = this.mFromdata;
            formSendData.id = this.nFromdata.id;
            formSendData.pmInsId = this.nFromdata.pmInsId;
            formSendData.processType = this.params.pmInsType
            formSendData.workItemId = this.params.workItemId;

            let currentUserCode = util.encrypt(this.user.userName);
            var params1 = {
                kv: {
                    currentUserCode: currentUserCode,
                    source: 'MOBILE',
                    location: this.params.location,
                    processInstId: this.params.processInstId,
                    processDefName: this.params.processDefName,
                    processType: this.params.pmInsType,
                },
            };

            var params2 = {
                kv: {
                    "currentUserCode": currentUserCode,
                    "source": 'MOBILE',
                    "location": this.params.location,
                    "processInstId": this.params.processInstId,
                    'processType': this.params.pmInsType,
                    'receiptCode': this.params.processInstId
                },
            };

            var params3 = {
                kv: {
                    "source": 'MOBILE',
                    "currentUserCode": currentUserCode,
                    "workItemId": this.params.todoType == 3 ? "" : this.params.workItemId,
                    "processInstId": this.params.processInstId,
                    "location": this.params.location,
                    "notificationId": this.params.todoType == 3 ? this.params.wfnid : "",
                    'processType': this.params.pmInsType,
                },
            };
            localStorage.setItem('submitPageParam', JSON.stringify({
                getDecisionsUrl: 'decisionAndUser$api$getDecisions',
                getUserUrl: 'decisionAndUser$api$getOrgAndUser',
                tosubmintUrl: 'applicationFormProject$api$startSubmitProcess',

                getDecisionsParams: params1,
                getUserParams: params2,
                tosubmintParams: params3,
                formData: formSendData,
                fromMoa: this.params.fromMoa,
                type: this.params.todoType == 3 ? "toRead" : "toDo"
            }));
            this.$router.push({
                name: "srqrsubmit"
            });
        },

        onSubmit() {
          if (this.formEditable&&this.analysisData&&this.analysisData.length>0&&this.sysFiles&&this.sysFiles.length>0){
            Toast.loading({ message: '数据保存中...', forbidClick: false });
            saveFileParsingRequestLog(Object.assign(this.params, { userName: this.user.userName,id:this.idKey ,fileId: this.sysFiles[0].id, detailData:this.analysisData })).then((result) => {
              Toast.clear();
              if (!result.data) {
                Notify(result.message);
                return;
              }
              if (result.data.errcode===0) {
                this.controlRule(this.params, this.mFromdata.projectID, function () {
                  this.onNext();
                }.bind(this));
              }
            })
          }
          else {
            this.controlRule(this.params, this.mFromdata.projectID, function () {
              this.onNext();
            }.bind(this));
          }
        },

    },
};
</script>

<style scoped>
/* @import url();*/
</style>